import cluster from "cluster";
import os from "os";
import http from "http";
import express from "express";
import { Server } from "socket.io";
import si from "systeminformation";
import axios from "axios";
const numCPUs = os.cpus().length;
if (!cluster.isWorker) {
  console.log(`Master ${process.pid} is running`);
  // 衍生工作进程。
  for (let i = 0; i < numCPUs; i++) {
    console.log(`Forking process number ${i}`);
    cluster.fork();
  }
  cluster.on("exit", (worker, code, signal) => {
    console.log(`worker ${worker.process.pid} died`);
  });

} else {
  // 工作进程可以共享任何TCP连接。
  // 在本例中，它是一个HTTP服务器
  const app = express();
  app.use(express.json())
  app.use(express.urlencoded({ extended: true }));  
  const server = http.createServer(app);
  const io = new Server(server);
  // 设置你的Express路由...
  
  // Socket.IO事件监听
  io.on("connection", (socket) => {
    console.log("一个用户已连接");

    socket.on("disconnect", () => {
      console.log("用户已断开连接");
    });

    // 监听客户端发来的'chat message'事件
    socket.on("chat message", (msg) => {
      io.emit("chat message", msg);
    });

    // 你还可以监听和处理更多的事件...
  });
  server.on("connect",(req, socket, head)=>{
    console.log("客户端已连接");
  })
  server.on("connection",async (socket)=>{
    
    console.log("服务器端已连接");
  })
  // 分别处理 查询参数 表单 json 上传文件 
  app.get("/query",async (req, res) => {
    console.log(req.query);
    res.send("query route");
  });
  app.post("/form", (req, res) => {
    console.log(req.body,req.headers);
    res.send("form route");
  });
  app.post("/json", (req, res) => {
    console.log(req.body,req.headers);
    res.send("json route");
  });
  app.post("/upload", (req, res) => {
    console.log(req.body);
    res.send("upload route");
  });

  let count = 0;
  app.get("/count",(req,res)=>{
    res.send(`当前计数：${count}`);
    count++;
  })

  app.get("/sysinfo", (req, res) => {

    async function getSystemInfo() {
      try {
          const osInfo = await si.osInfo();
          const cpuInfo = await si.cpu();
          const memInfo = await si.mem();
          const diskInfo = await si.fsSize();
          const networkInfo = await si.networkInterfaces();
          const loadInfo = await si.currentLoad();
          res.send({
            osInfo,
            cpuInfo,
            memInfo,
            diskInfo,
            networkInfo,
            loadInfo
          })
      } catch (error) {
          console.error(error);
      }
  }
  
  getSystemInfo();
  })

  app.get("/getnet",async(req,res)=>{
    const data = await axios.get("https://qifu-api.baidubce.com/ip/local/geo/v1/district")
    res.send(data.data)
  })
  // 启动HTTP服务器
  const PORT = process.env.PORT || 80;
  server.listen(PORT, () => {
    console.log(`服务器正在监听端口 ${PORT}`);
  });
  console.log(`Worker ${process.pid} started`);
}
